// pages/index/goodsDetail/goodsDetail.js
var app = getApp();
import Api from '../../../api/api.js';
const api = new Api();
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banderList: [],
    detailImageList: [],
    detailDict:{},
    currentSkuDict:{},
    skuList:[],
    cityName:"",
    buyListData:{},
    skuSelectIndex:0,
    isShowType:false,
    productId:"",
    postId:null,
    sourcePage:"",
    isAuthorization: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var productId = options.productId;
    this.data.productId = productId;
    this.data.sourcePage = options.page;
    this.setData({
      sourcePage:this.data.sourcePage
    });
    if (options.postId){
      this.data.postId = options.postId;
    }
    this.getUserData();
    qqmapsdk = new QQMapWX({
      key: app.qqmapkey
    });
    this.getCurrentLoaction();
  },
  getListData() {
    var _this = this;
    var map = {};
    map.productId = this.data.productId;
    api.getRequestData(app.goodsDetailUrl, map, true, "GET").then(res => {
      if (res.data.errorCode == 0) {
        var list = res.data.model.imgs;
        for (var i = 0; i < list.length; i++) {
          var dic = list[i];
          if (dic.type == 1) {
            _this.data.banderList.push(dic);
          } else if (dic.type == 2) {
            _this.data.detailImageList.push(dic);
          }
        }
        var list = res.data.model.skus;
        var dict = list[0];
        dict.selectCount = 1;
       _this.setData({
         banderList: _this.data.banderList,
         detailImageList: _this.data.detailImageList,
         detailDict: res.data.model,
         currentSkuDict: dict,
         skuList:list
       });
        _this.getBuyList(_this.data.productId);
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  getBuyList(productId){
    var _this = this;
    var map = {};
    map.productId = productId;
    map.pageIndex = 1;
    map.pageCount = 10;
    api.getRequestData(app.buyGoodsListUrl, map, true, "POST").then(res => {
      if (res.data.errorCode == 0) {
        var dict = res.data.model;
        _this.setData({
          buyListData: dict
        });
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  imageItemClick(e){
    var index = parseInt(e.currentTarget.dataset.key);
    var list = this.data.banderList;
    var tempList = [];
    var temUrl = "";
    for (var i = 0;i< list.length;i++){
      var dict = list[i];
      var url = dict.url;
      tempList.push(url);
      if (i == index){
        temUrl = url;
      }
    }
    wx.previewImage({
      current: temUrl,
      urls: tempList,
    })
  },
  getCurrentLoaction: function () {
    var _this = this;
    wx.showLoading({
      title: '获取位置...',
    })
    wx.getLocation({
      type: "gcj02",
      success: function (res) {
        wx.hideLoading();
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            var result = addressRes.result;
            if (result) {
              var cityName = result.address_component.city;
             _this.setData({
               cityName:cityName
             });
            }
          },
          fail(res) {

          }
        })
      },
      fail(res) {
        wx.hideLoading();

      }
    })
  },

  goToMineCart(){
    wx.navigateTo({
      url: '/pages/mine/shopCart/shopCart',
    })
  },
  addGoodToCart(){
    this.setData({
      isShowType:false
    });
    var dict =  this.data.currentSkuDict;
    var _this = this;
    var map = {};
    if (this.data.postId){
      map.contentId = this.data.postId;
    }
    map.productId = dict.productId;
    map.qty = dict.selectCount+"";
    map.skuId = dict.id;
    map.type = "5";
    map.appId = app.APP_ID;
    map.userId = app.USER_ID();;

    api.getRequestData(app.saveCartUrl, map, true, "POST").then(res => {
      if (res.data.errorCode == 0) {
          app.alert("添加购物车成功~");
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  typeClick(){
    this.setData({
      isShowType: true
    });
  },
  typeViewClick(){
    this.setData({
      isShowType:false
    });
  },
  sukDataClick(e){
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.skuList[index];
    var stock = parseInt(dict.stock);
    if (stock <= 0){
      app.alert("库存不足~");
      return;
    }
    this.setData({
      currentSkuDict:dict
    });
  },
  subCountClick(){
    var dict = this.data.currentSkuDict;
    var count = parseInt(dict.selectCount);
    if (count <= 1) {
      app.alert("数量不能再少了~");
      return;
    }
    count -= 1;
    dict.selectCount = count;
    this.setData({
      currentSkuDict: dict
    });
  },
  addCountClick(){
    var dict = this.data.currentSkuDict;
    var count = parseInt(dict.selectCount);
    var stock = parseInt(dict.stock);
    if (count + 1 > stock) {
      app.alert("库存不足~");
      return;
    }
    if (count + 1 > 99) {
      app.alert("购买数量上限~");
      return;
    }
    count += 1;
    dict.selectCount = count;
    this.setData({
      currentSkuDict: dict
    });
  },
  buyNowClick(){
    this.setData({
      isShowType:false
    });
    // 开始购买
    this.data.currentSkuDict.productName = this.data.detailDict.product.name;
    this.data.currentSkuDict.skuName = this.data.currentSkuDict.name;
    this.data.currentSkuDict.skuImg = this.data.currentSkuDict.img;
    this.data.currentSkuDict.skuId = this.data.currentSkuDict.id;
    this.data.currentSkuDict.note = this.data.detailDict.product.note;
    if (this.data.postId){
      this.data.currentSkuDict.contentId = this.data.postId;
    }
    var list = [];
    list.push(this.data.currentSkuDict);
    var listString = JSON.stringify(list);
    wx.setStorageSync("payList", listString);
    var url = '/pages/index/createOrder/createOrder';
    if (this.data.postId){
      url = '/pages/index/createOrder/createOrder?postId=' + this.data.postId;
    }
    wx.navigateTo({
      url: url,
    })
  },
  lookAllClick(){
    wx.navigateTo({
      url: '/pages/index/goodsDetail/moreBuyList/moreBuyList?productId=' + this.data.productId,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getUserData() {
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res) {
        app.getOpenIdData().then(res => {
          _this.getListData();
        });
      }
    });
  },
  // 获取用户信息
  getNewUserInfo(e) {
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res) {
        app.getOpenIdData().then(res => {
          _this.getListData();
        });
      }

    });
  },
})